home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / file / fileutil.13 / fileutil / fileutils-3.13 / src / install.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-07-10  |  15.6 KB  |  620 lines

  1. /* install - copy files and set attributes
  2.    Copyright (C) 89, 90, 91, 95, 1996 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software Foundation,
  16.    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  17.  
  18. /* Copy files and set their permission modes and, if possible,
  19.    their owner and group.  Used similarly to `cp'; typically
  20.    used in Makefiles to copy programs into their destination
  21.    directories.  It can also be used to create the destination
  22.    directories and any leading directories, and to set the final
  23.    directory's modes.  It refuses to copy files onto themselves.
  24.  
  25.    Options:
  26.    -g, --group=GROUP
  27.     Set the group ownership of the installed file or directory
  28.     to the group ID of GROUP (default is process's current
  29.     group).  GROUP may also be a numeric group ID.
  30.  
  31.    -m, --mode=MODE
  32.     Set the permission mode for the installed file or directory
  33.     to MODE, which is an octal number (default is 0755).
  34.  
  35.    -o, --owner=OWNER
  36.     If run as root, set the ownership of the installed file to
  37.     the user ID of OWNER (default is root).  OWNER may also be
  38.     a numeric user ID.
  39.  
  40.    -c    No effect.  For compatibility with old Unix versions of install.
  41.  
  42.    -s, --strip
  43.     Strip the symbol tables from installed files.
  44.  
  45.    -d, --directory
  46.     Create a directory and its leading directories, if they
  47.     do not already exist.  Set the owner, group and mode
  48.     as given on the command line.  Any leading directories
  49.     that are created are also given those attributes.
  50.     This is different from the SunOS 4.0 install, which gives
  51.     directories that it creates the default attributes.
  52.  
  53.    David MacKenzie <djm@gnu.ai.mit.edu> */
  54.  
  55. #include <config.h>
  56. #include <stdio.h>
  57. #include <getopt.h>
  58. #include <sys/types.h>
  59. #include <pwd.h>
  60. #include <grp.h>
  61.  
  62. #include "system.h"
  63. #include "backupfile.h"
  64. #include "modechange.h"
  65. #include "makepath.h"
  66. #include "error.h"
  67. #include "xstrtol.h"
  68.  
  69. #if HAVE_SYS_WAIT_H
  70. # include <sys/wait.h>
  71. #endif
  72.  
  73. #if HAVE_VALUES_H
  74. # include <values.h>
  75. #endif
  76.  
  77. #ifndef BITSPERBYTE
  78. # define BITSPERBYTE 8
  79. #endif
  80.  
  81. struct passwd *getpwnam ();
  82. struct group *getgrnam ();
  83.  
  84. #ifndef _POSIX_VERSION
  85. uid_t getuid ();
  86. gid_t getgid ();
  87. int wait ();
  88. #endif
  89.  
  90. #ifndef HAVE_ENDGRENT
  91. # define endgrent() ((void) 0)
  92. #endif
  93.  
  94. #ifndef HAVE_ENDPWENT
  95. # define endpwent() ((void) 0)
  96. #endif
  97.  
  98. /* True if C is an ASCII octal digit. */
  99. #define isodigit(c) ((c) >= '0' && c <= '7')
  100.  
  101. /* Number of bytes of a file to copy at a time. */
  102. #define READ_SIZE (32 * 1024)
  103.  
  104. #ifndef UID_T_MAX
  105. # define UID_T_MAX ((uid_t)(~((unsigned long)1 << ((sizeof (uid_t) \
  106.                             * BITSPERBYTE - 1)))))
  107. #endif
  108.  
  109. #ifndef GID_T_MAX
  110. # define GID_T_MAX ((gid_t)(~((unsigned long)1 << ((sizeof (gid_t) \
  111.                             * BITSPERBYTE - 1)))))
  112. #endif
  113.  
  114. char *basename ();
  115. char *stpcpy ();
  116. char *xmalloc ();
  117. int safe_read ();
  118. int full_write ();
  119. int isdir ();
  120. enum backup_type get_version ();
  121.  
  122. static int change_attributes __P ((char *path, int no_need_to_chown));
  123. static int copy_file __P ((char *from, char *to, int *to_created));
  124. static int install_file_in_dir __P ((char *from, char *to_dir));
  125. static int install_file_in_file __P ((char *from, char *to));
  126. static void get_ids __P ((void));
  127. static void strip __P ((char *path));
  128. static void usage __P ((int status));
  129.  
  130. /* The name this program was run with, for error messages. */
  131. char *program_name;
  132.  
  133. /* The user name that will own the files, or NULL to make the owner
  134.    the current user ID. */
  135. static char *owner_name;
  136.  
  137. /* The user ID corresponding to `owner_name'. */
  138. static uid_t owner_id;
  139.  
  140. /* The group name that will own the files, or NULL to make the group
  141.    the current group ID. */
  142. static char *group_name;
  143.  
  144. /* The group ID corresponding to `group_name'. */
  145. static gid_t group_id;
  146.  
  147. /* The permissions to which the files will be set.  The umask has
  148.    no effect. */
  149. static int mode;
  150.  
  151. /* If nonzero, strip executable files after copying them. */
  152. static int strip_files;
  153.  
  154. /* If nonzero, install a directory instead of a regular file. */
  155. static int dir_arg;
  156.  
  157. /* If nonzero, display usage information and exit.  */
  158. static int show_help;
  159.  
  160. /* If nonzero, print the version on standard output and exit.  */
  161. static int show_version;
  162.  
  163. static struct option const long_options[] =
  164. {
  165.   {"strip", no_argument, NULL, 's'},
  166.   {"directory", no_argument, NULL, 'd'},
  167.   {"group", required_argument, NULL, 'g'},
  168.   {"mode", required_argument, NULL, 'm'},
  169.   {"owner", required_argument, NULL, 'o'},
  170.   {"backup", no_argument, NULL, 'b'},
  171.   {"version-control", required_argument, NULL, 'V'},
  172.   {"help", no_argument, &show_help, 1},
  173.   {"version", no_argument, &show_version, 1},
  174.   {NULL, 0, NULL, 0}
  175. };
  176.  
  177. int
  178. main (int argc, char **argv)
  179. {
  180.   int optc;
  181.   int errors = 0;
  182.   char *symbolic_mode = NULL;
  183.   int make_backups = 0;
  184.   char *version;
  185.  
  186.   program_name = argv[0];
  187.   setlocale (LC_ALL, "");
  188.   bindtextdomain (PACKAGE, LOCALEDIR);
  189.   textdomain (PACKAGE);
  190.  
  191.   owner_name = NULL;
  192.   group_name = NULL;
  193.   mode = 0755;
  194.   strip_files = 0;
  195.   dir_arg = 0;
  196.   umask (0);
  197.  
  198.    version = getenv ("SIMPLE_BACKUP_SUFFIX");
  199.    if (version)
  200.       simple_backup_suffix = version;
  201.    version = getenv ("VERSION_CONTROL");
  202.  
  203.   while ((optc = getopt_long (argc, argv, "bcsdg:m:o:V:S:", long_options,
  204.                   (int *) 0)) != EOF)
  205.     {
  206.       switch (optc)
  207.     {
  208.     case 0:
  209.       break;
  210.     case 'b':
  211.       make_backups = 1;
  212.       break;
  213.     case 'c':
  214.       break;
  215.     case 's':
  216.       strip_files = 1;
  217.       break;
  218.     case 'd':
  219.       dir_arg = 1;
  220.       break;
  221.     case 'g':
  222.       group_name = optarg;
  223.       break;
  224.     case 'm':
  225.       symbolic_mode = optarg;
  226.       break;
  227.     case 'o':
  228.       owner_name = optarg;
  229.       break;
  230.     case 'S':
  231.       simple_backup_suffix = optarg;
  232.       break;
  233.         case 'V':
  234.       version = optarg;
  235.       break;
  236.     default:
  237.       usage (1);
  238.     }
  239.     }
  240.  
  241.   if (show_version)
  242.     {
  243.       printf ("install - %s\n", PACKAGE_VERSION);
  244.       exit (0);
  245.     }
  246.  
  247.   if (show_help)
  248.     usage (0);
  249.  
  250.   /* Check for invalid combinations of arguments. */
  251.   if (dir_arg && strip_files)
  252.     error (1, 0,
  253.        _("the strip option may not be used when installing a directory"));
  254.  
  255.   if (make_backups)
  256.     backup_type = get_version (version);
  257.  
  258.   if (optind == argc || (optind == argc - 1 && !dir_arg))
  259.     {
  260.       error (0, 0, _("too few arguments"));
  261.       usage (1);
  262.     }
  263.  
  264.   if (symbolic_mode)
  265.     {
  266.       struct mode_change *change = mode_compile (symbolic_mode, 0);
  267.       if (change == MODE_INVALID)
  268.     error (1, 0, _("invalid mode `%s'"), symbolic_mode);
  269.       else if (change == MODE_MEMORY_EXHAUSTED)
  270.     error (1, 0, _("virtual memory exhausted"));
  271.       mode = mode_adjust (0, change);
  272.     }
  273.  
  274.   get_ids ();
  275.  
  276.   if (dir_arg)
  277.     {
  278.       for (; optind < argc; ++optind)
  279.     {
  280.       errors |=
  281.         make_path (argv[optind], mode, mode, owner_id, group_id, 0, NULL);
  282.     }
  283.     }
  284.   else
  285.     {
  286.       if (optind == argc - 2)
  287.     {
  288.       if (!isdir (argv[argc - 1]))
  289.         errors = install_file_in_file (argv[argc - 2], argv[argc - 1]);
  290.       else
  291.         errors = install_file_in_dir (argv[argc - 2], argv[argc - 1]);
  292.     }
  293.       else
  294.     {
  295.       if (!isdir (argv[argc - 1]))
  296.         usage (1);
  297.       for (; optind < argc - 1; ++optind)
  298.         {
  299.           errors |= install_file_in_dir (argv[optind], argv[argc - 1]);
  300.         }
  301.     }
  302.     }
  303.  
  304.   exit (errors);
  305. }
  306.  
  307. /* Copy file FROM onto file TO and give TO the appropriate
  308.    attributes.
  309.    Return 0 if successful, 1 if an error occurs. */
  310.  
  311. static int
  312. install_file_in_file (char *from, char *to)
  313. {
  314.   int to_created;
  315.   int no_need_to_chown;
  316.  
  317.   if (copy_file (from, to, &to_created))
  318.     return 1;
  319.   if (strip_files)
  320.     strip (to);
  321.   no_need_to_chown = (to_created
  322.               && owner_name == NULL
  323.               && group_name == NULL);
  324.   return change_attributes (to, no_need_to_chown);
  325. }
  326.  
  327. /* Copy file FROM into directory TO_DIR, keeping its same name,
  328.    and give the copy the appropriate attributes.
  329.    Return 0 if successful, 1 if not. */
  330.  
  331. static int
  332. install_file_in_dir (char *from, char *to_dir)
  333. {
  334.   char *from_base;
  335.   char *to;
  336.   int ret;
  337.  
  338.   from_base = basename (from);
  339.   to = xmalloc ((unsigned) (strlen (to_dir) + strlen (from_base) + 2));
  340.   stpcpy (stpcpy (stpcpy (to, to_dir), "/"), from_base);
  341.   ret = install_file_in_file (from, to);
  342.   free (to);
  343.   return ret;
  344. }
  345.  
  346. /* A chunk of a file being copied. */
  347. static char buffer[READ_SIZE];
  348.  
  349. /* Copy file FROM onto file TO, creating TO if necessary.
  350.    Return 0 if the copy is successful, 1 if not.  If the copy is
  351.    successful, set *TO_CREATED to nonzero if TO was created (if it did
  352.    not exist or did, but was unlinked) and to zero otherwise.  If the
  353.    copy fails, don't modify *TO_CREATED.  */
  354.  
  355. static int
  356. copy_file (char *from, char *to, int *to_created)
  357. {
  358.   int fromfd, tofd;
  359.   int bytes;
  360.   int ret = 0;
  361.   struct stat from_stats, to_stats;
  362.   int target_created = 1;
  363.  
  364.   if (stat (from, &from_stats))
  365.     {
  366.       error (0, errno, "%s", from);
  367.       return 1;
  368.     }
  369.   if (!S_ISREG (from_stats.st_mode))
  370.     {
  371.       error (0, 0, _("`%s' is not a regular file"), from);
  372.       return 1;
  373.     }
  374.   if (stat (to, &to_stats) == 0)
  375.     {
  376.       if (!S_ISREG (to_stats.st_mode))
  377.     {
  378.       error (0, 0, _("`%s' is not a regular file"), to);
  379.       return 1;
  380.     }
  381.       if (from_stats.st_dev == to_stats.st_dev
  382.       && from_stats.st_ino == to_stats.st_ino)
  383.     {
  384.       error (0, 0, _("`%s' and `%s' are the same file"), from, to);
  385.       return 1;
  386.     }
  387.  
  388.       /* The destination file exists.  Try to back it up if required.  */
  389.       if (backup_type != none)
  390.         {
  391.       char *tmp_backup = find_backup_file_name (to);
  392.       char *dst_backup;
  393.  
  394.       if (tmp_backup == NULL)
  395.         error (1, 0, "virtual memory exhausted");
  396.       dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
  397.       strcpy (dst_backup, tmp_backup);
  398.       free (tmp_backup);
  399.       if (rename (to, dst_backup))
  400.         {
  401.           if (errno != ENOENT)
  402.         {
  403.           error (0, errno, "cannot backup `%s'", to);
  404.           return 1;
  405.         }
  406.         }
  407.     }
  408.  
  409.       /* If unlink fails, try to proceed anyway.  */
  410.       if (unlink (to))
  411.     target_created = 0;
  412.     }
  413.  
  414.   fromfd = open (from, O_RDONLY, 0);
  415.   if (fromfd == -1)
  416.     {
  417.       error (0, errno, "%s", from);
  418.       return 1;
  419.     }
  420.  
  421.   /* Make sure to open the file in a mode that allows writing. */
  422.   tofd = open (to, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  423.   if (tofd == -1)
  424.     {
  425.       error (0, errno, "%s", to);
  426.       close (fromfd);
  427.       return 1;
  428.     }
  429.  
  430.   while ((bytes = safe_read (fromfd, buffer, READ_SIZE)) > 0)
  431.     if (full_write (tofd, buffer, bytes) < 0)
  432.       {
  433.     error (0, errno, "%s", to);
  434.     goto copy_error;
  435.       }
  436.  
  437.   if (bytes == -1)
  438.     {
  439.       error (0, errno, "%s", from);
  440.       goto copy_error;
  441.     }
  442.  
  443.   if (close (fromfd) < 0)
  444.     {
  445.       error (0, errno, "%s", from);
  446.       ret = 1;
  447.     }
  448.   if (close (tofd) < 0)
  449.     {
  450.       error (0, errno, "%s", to);
  451.       ret = 1;
  452.     }
  453.   if (ret == 0)
  454.     *to_created = target_created;
  455.   return ret;
  456.  
  457.  copy_error:
  458.   close (fromfd);
  459.   close (tofd);
  460.   return 1;
  461. }
  462.  
  463. /* Set the attributes of file or directory PATH.
  464.    If NO_NEED_TO_CHOWN is nonzero, don't call chown.
  465.    Return 0 if successful, 1 if not. */
  466.  
  467. static int
  468. change_attributes (char *path, int no_need_to_chown)
  469. {
  470.   int err = 0;
  471.  
  472.   /* chown must precede chmod because on some systems,
  473.      chown clears the set[ug]id bits for non-superusers,
  474.      resulting in incorrect permissions.
  475.      On System V, users can give away files with chown and then not
  476.      be able to chmod them.  So don't give files away.
  477.  
  478.      We don't pass -1 to chown to mean "don't change the value"
  479.      because SVR3 and earlier non-BSD systems don't support that.
  480.  
  481.      We don't normally ignore errors from chown because the idea of
  482.      the install command is that the file is supposed to end up with
  483.      precisely the attributes that the user specified (or defaulted).
  484.      If the file doesn't end up with the group they asked for, they'll
  485.      want to know.  But AFS returns EPERM when you try to change a
  486.      file's group; thus the kludge.  */
  487.  
  488.   if (!no_need_to_chown && chown (path, owner_id, group_id)
  489. #ifdef AFS
  490.       && errno != EPERM
  491. #endif
  492.       )
  493.     err = errno;
  494.   if (chmod (path, mode))
  495.     err = errno;
  496.   if (err)
  497.     {
  498.       error (0, err, "%s", path);
  499.       return 1;
  500.     }
  501.   return 0;
  502. }
  503.  
  504. /* Strip the symbol table from the file PATH.
  505.    We could dig the magic number out of the file first to
  506.    determine whether to strip it, but the header files and
  507.    magic numbers vary so much from system to system that making
  508.    it portable would be very difficult.  Not worth the effort. */
  509.  
  510. static void
  511. strip (char *path)
  512. {
  513.   int pid, status;
  514.  
  515.   pid = fork ();
  516.   switch (pid)
  517.     {
  518.     case -1:
  519.       error (1, errno, _("cannot fork"));
  520.       break;
  521.     case 0:            /* Child. */
  522.       execlp ("strip", "strip", path, (char *) NULL);
  523.       error (1, errno, _("cannot run strip"));
  524.       break;
  525.     default:            /* Parent. */
  526.       /* Parent process. */
  527.       while (pid != wait (&status))    /* Wait for kid to finish. */
  528.     /* Do nothing. */ ;
  529.       break;
  530.     }
  531. }
  532.  
  533. /* Initialize the user and group ownership of the files to install. */
  534.  
  535. static void
  536. get_ids (void)
  537. {
  538.   struct passwd *pw;
  539.   struct group *gr;
  540.  
  541.   if (owner_name)
  542.     {
  543.       pw = getpwnam (owner_name);
  544.       if (pw == NULL)
  545.     {
  546.       long int tmp_long;
  547.       if (xstrtol (owner_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
  548.           || tmp_long < 0 || tmp_long > UID_T_MAX)
  549.         error (1, 0, _("invalid user `%s'"), owner_name);
  550.       owner_id = (uid_t) tmp_long;
  551.     }
  552.       else
  553.     owner_id = pw->pw_uid;
  554.       endpwent ();
  555.     }
  556.   else
  557.     owner_id = getuid ();
  558.  
  559.   if (group_name)
  560.     {
  561.       gr = getgrnam (group_name);
  562.       if (gr == NULL)
  563.     {
  564.       long int tmp_long;
  565.       if (xstrtol (group_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
  566.           || tmp_long < 0 || tmp_long > (long) GID_T_MAX)
  567.         error (1, 0, _("invalid group `%s'"), group_name);
  568.       group_id = (gid_t) tmp_long;
  569.     }
  570.       else
  571.     group_id = gr->gr_gid;
  572.       endgrent ();
  573.     }
  574.   else
  575.     group_id = getgid ();
  576. }
  577.  
  578. static void
  579. usage (int status)
  580. {
  581.   if (status != 0)
  582.     fprintf (stderr, _("Try `%s --help' for more information.\n"),
  583.          program_name);
  584.   else
  585.     {
  586.       printf (_("\
  587. Usage: %s [OPTION]... SOURCE DEST           (1st format)\n\
  588.   or:  %s [OPTION]... SOURCE... DIRECTORY   (2nd format)\n\
  589.   or:  %s -d [OPTION]... DIRECTORY...       (3rd format)\n\
  590. "),
  591.           program_name, program_name, program_name);
  592.       printf (_("\
  593. In first two formats, copy SOURCE to DEST or multiple SOURCE(s) to\n\
  594. DIRECTORY, while setting permission modes and owner/group.  In third\n\
  595. format, make all components of the given DIRECTORY(ies).\n\
  596. \n\
  597.   -c                  (ignored)\n\
  598.   -d, --directory     create [leading] directories, mandatory for 3rd format\n\
  599.   -g, --group=GROUP   set group ownership, instead of process' current group\n\
  600.   -m, --mode=MODE     set permission mode (as in chmod), instead of rw-r--r--\n\
  601.   -o, --owner=OWNER   set ownership (super-user only)\n\
  602.   -s, --strip         strip symbol tables, only for 1st and 2nd formats\n\
  603.   -b, --backup        make backup before removal\n\
  604.   -S, --suffix=SUFFIX override the usual backup suffix\n\
  605.   -V, --version-control=WORD   override the usual version control\n\
  606.       --help          display this help and exit\n\
  607.       --version       output version information and exit\n\
  608. \n\
  609. "));
  610.       printf (_("\
  611. The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
  612. version control may be set with VERSION_CONTROL, values are:\n\
  613. \n\
  614.   t, numbered     make numbered backups\n\
  615.   nil, existing   numbered if numbered backups exist, simple otherwise\n\
  616.   never, simple   always make simple backups\n"));
  617.     }
  618.   exit (status);
  619. }
  620.